package com.youboy.oauth;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.youboy.oauth.common.OAuthCodec;
import com.youboy.oauth.common.OAuthParameters;
import com.youboy.oauth.model.OAuthConsumerAuthentication;
import com.youboy.oauth.token.OAuthToken;

/**
 * 
 * @author loudyn
 * 
 */
public class OAuthRequestTokenFilter extends OAuthProcessFilterSupport {

	@Override
	protected void onValidOAuthAuthentication(OAuthConsumerAuthentication consumerAuthentication, HttpServletRequest request,
											HttpServletResponse response, FilterChain chain) throws Exception {

		OAuthToken requestToken = createOAuthRequestToken(consumerAuthentication);
		renderRequestToken(requestToken, response);
	}

	private OAuthToken createOAuthRequestToken(OAuthConsumerAuthentication consumerAuthentication) {

		return getTokenService().createUnauthorizedRequestToken(
																consumerAuthentication.getOAuthConsumer().getConsumerKey(),
																consumerAuthentication.getOAuthParameters().get(
																		OAuthParameters.OAUTH_CALLBACK.asString()
																		)
															);
	}

	private void renderRequestToken(OAuthToken requestToken, ServletResponse response) throws IOException {
		StringBuilder responseValue = new StringBuilder().append(OAuthParameters.OAUTH_TOKEN.asString())
															.append("=")
															.append(OAuthCodec.oauthEncode(requestToken.getValue()))
															.append("&")
															.append(OAuthParameters.OAUTH_TOKEN_SECRET.asString())
															.append("=")
															.append(OAuthCodec.oauthEncode(requestToken.getSecret()));

		if (StringUtils.isNotBlank(requestToken.getCallbackUrl())) {
			responseValue.append("&").append(OAuthParameters.OAUTH_CALLBACK_CONFIRMED.asString())
							.append("=").append(Boolean.TRUE);
		}

		response.setContentType("text/plain;charset=utf-8");
		response.getWriter().print(responseValue.toString());
		response.flushBuffer();
	}

}
